<template>
  <div class="search-container">
    <!-- 顶部的搜索栏 -->
    <form
      action="/"
      class="searchForm"
    >
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <searchResult
      v-if="isResultShow"
      :search-text='searchText'
    />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <searchSuggestion
      v-else-if="searchText"
      :search-text='searchText'
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <searchHistory
      v-else
      :search-histories="searchHistories"
      @clear-search-histories='searchHistories= []'
      @search='onSearch'
    />
    <!-- /搜索历史记录 -->

  </div>
</template>

<script>
import searchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResult from './components/search-result.vue'

import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  watch: {
    searchHistories (val) {
      // 同步到本地存储
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.searchText = val

      // 更新文本框内容
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)

      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .searchForm {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
